﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using OccupierArchiver.DataClasses;
using OccupierArchiver.DataRepository;
using OccupierArchiver.Helpers;

namespace OccupierArchiver.UserInterface
{
    public partial class FormMain : Form
    {
        private DataTable _tblItems;
        private const string OilUrl = "http://occupier.hk/standbyyou/archive.php?page=";

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            var bs = new BindingSource();
            _tblItems = DataTables.TblMessage;
            bs.DataSource = _tblItems;
            dgvItems.DataSource = bs;
            dgvItems.Columns[0].Width = 80;
            dgvItems.Columns[1].Width = 160;
            dgvItems.Columns[2].Width = 160;
            dgvItems.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        private void ReloadData()
        {
            ClearDataTable();
            CurlDownloader.GlobalInit();
            int pCount;
            using (var cd = new CurlDownloader())
            {
                string filed = Program.TempDir + "\\" + Guid.NewGuid() + ".html";
                cd.DownloadFile(OilUrl + "1", filed);
                pCount = MessageDao.GetPageCount(filed);
                File.Delete(filed);
            }
            // for (var i = 1; i < pCount; i++)
            // Reverse enumeration is to maintain each record's id
            for (int i = pCount - 1; i >= 0; i--)
            {
                using (var cd = new CurlDownloader())
                {
                    string filed = Program.TempDir + "\\" + Guid.NewGuid() + ".html";
                    cd.DownloadFile(OilUrl + i, filed);
                    var ap = MessageDao.GetListMessage(filed).ToArray();
                    foreach (var item in ap.Reverse())
                    {
                        _tblItems.Rows.Add(item.ToArray());
                    }
                    File.Delete(filed);
                }
            }
            CurlDownloader.GlobalCleanup();
        }

        private void ClearDataTable()
        {
            _tblItems.Clear();
            _tblItems.Columns[0].AutoIncrementStep = -1;
            _tblItems.Columns[0].AutoIncrementSeed = -1;
            _tblItems.Columns[0].AutoIncrementStep = 1;
            _tblItems.Columns[0].AutoIncrementSeed = 1;
        }

        private void mnuReload_Click(object sender, EventArgs e)
        {
            ReloadData();
        }

        private void exportToSQLFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var exporter = new DataExporter(_tblItems);
            exporter.ExportToSql("exported.sql");
        }

    }
}
